package applicationutil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;

import luceneutil.V100LunceneWorker;
import net.java.textilej.parser.MarkupParser;
import net.java.textilej.parser.builder.HtmlDocumentBuilder;
import net.java.textilej.parser.markup.mediawiki.MediaWikiDialect;
import net.sourceforge.vietpad.utilities.VietUtilities;

import org.apache.commons.validator.UrlValidator;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.primefaces.context.RequestContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import bean.IndexControl;
import dao.V100Dao;
import vn.hus.nlp.tokenizer.VietTokenizer;
import entities.V100;

/**
 * @author thoai nguyen
 * 
 */

public class ApplicationUtil {
	public static VietTokenizer vietTokenizer = new VietTokenizer();

	public static void showMessage(String title) {
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, new FacesMessage(title));
	}

	public static Object getService(String bean) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"Spring-Module.xml");
		return context.getBean(bean);
	}

	public static HttpServletRequest getRequest() {
		ExternalContext context = FacesContext.getCurrentInstance()
				.getExternalContext();
		return (HttpServletRequest) context.getRequest();
	}

	public static void navigateTo(String url) {
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			context.getExternalContext().redirect(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getRequestURL() {
		HttpServletRequest origRequest = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		return origRequest.getRequestURL().toString();
	}

	public static void setSession(String name, Object object) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();

		HttpSession httpSession = request.getSession(false);
		httpSession.setAttribute(name, object);
	}

	public static Object getSession(String name) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		HttpSession httpSession = request.getSession(false);
		Object reqdObj = (Object) httpSession.getAttribute(name);
		return reqdObj;
	}

	public static void removeSession(String name) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		HttpSession httpSession = request.getSession(false);
		httpSession.removeAttribute(name);
	}

	/*
	 * them dau vao tu
	 */
	public static String addAccent(String s) {
		return VietUtilities.addDiacritics(s, new File(
				ApplicationConstant.URL_VIETPAP));
	}

	/*
	 * loai bo het dau
	 */
	public static String removeAccent(String s) {
		return VietUtilities.stripDiacritics(s);
	}

	/*
	 * tach tu
	 */
	public synchronized static String getToken(String s) {
		String[] tokens = vietTokenizer.tokenize(s);
		if (tokens != null && tokens.length > 0)
			return tokens[0];
		else {
			System.out.println("------no token  found");
			return null;
		}
	}

	public static String getTextUrlForIndex(String orgUrl) {
		String url = orgUrl.replace("http", "").replace("/", " ")
				.replace(".", " ").replace(":", "");
		return url;
	}

	/*
	 * lay noi dung update lai v100
	 */
	public static void getInforFromURL(V100 v100) {
		V100Dao v100Dao = (V100Dao) ApplicationUtil.getService("v100DAO");
		try {
			System.out.println("--conecting to:" + v100.getVv101());
			ApplicationUtil.addToLog("--Conecting to:" + v100.getVv101());
			if (Jsoup.connect(v100.getVv101()) != null) {
				Document doc = Jsoup.connect(v100.getVv101()).get();

				if (doc != null) {
					// lay abs url chon index
					Element link = doc.select("a").first();
					String absHref = link.attr("abs:href");
					if (absHref != null && absHref.length() > 1)
						v100.setUrlIndex(ApplicationUtil
								.getTextUrlForIndex(absHref));
					else
						v100.setUrlIndex(ApplicationUtil
								.getTextUrlForIndex(v100.getVv101()));

					// lay noi dung
					v100.setVv103(doc.text());
					System.out
							.println("---------token:" + v100.getVv103token());
					// lay title
					v100.setVv102(doc.title());
					// lay link
					List<String> subUrls = new ArrayList<String>();
					Elements links = doc.select("a[href]");
					for (Element l : links) {
						String s = l.attr("abs:href");
						subUrls.add(s);
					}
					v100.setSubUrls(subUrls);
				} else {
					ApplicationUtil.addToLog("--Can'nt conect to url:"
							+ v100.getVv101());
					v100Dao.setError(v100.getPv100());
				}
			} else {
				ApplicationUtil.addToLog("--Can'nt conect to url:"
						+ v100.getVv101());
				v100Dao.setError(v100.getPv100());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			/*
			 * khi loi connect thi xoa trong db va xoa chi muc
			 */
			System.out.println("--loi khi get url:" + v100.getVv101());
			ApplicationUtil.addToLog("--Can'nt conect to url:"
					+ v100.getVv101());
			v100Dao.setError(v100.getPv100());
			e.printStackTrace();
			return;
		} 
	}

	public static String convertToMD5(String arg) {
		String hashed_key = "";

		try {
			byte[] intext = arg.getBytes();
			StringBuffer sb = new StringBuffer();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] md5rslt = md5.digest(intext);
			for (int i = 0; i < md5rslt.length; i++) {
				sb.append(String.format("%02x", 0xff & md5rslt[i]));
			}
			hashed_key = sb.toString();
		} catch (Exception e2) {
			System.out.println(e2);
		}
		return hashed_key;
	}

	public static String getBabSubContent(String text) {
		if (text.length() > 400) {
			text=text.substring(0,200);
		}
		return text+"...";
	}

	public static String getSubContentDefault(String orgTextSearch,
			String orgText) {

		String textSearch = ApplicationUtil.removeAccent(
				orgTextSearch.replace("\"", "").replace("_", " "))
				.toLowerCase();
		String text = ApplicationUtil.removeAccent(
				orgText.replace("\"", "").replace("_", " ")).toLowerCase();
		int f = text.indexOf(textSearch);
		if (f >= 0) {
			try {
				StringBuilder builder = new StringBuilder(orgText);
				int start;
				int end;
				/* them html code */
				// System.out.println("----test thu:"+builder.substring(f,f+textSearch.length()));
				builder.insert(f,
						"<label style=\"color:#551A8B;font-weight: bold;\" >");
				builder.insert(f + 49 + textSearch.length(), "</label>");

				start = f - 200;
				end = f + 200;
				if (start < 0)
					start = 0;
				if (end > builder.length())
					end = builder.length() - 1;
				/*
				 * System.out.println("---build lenght:"+builder.length());
				 * System.out.println("---start:"+start);
				 * System.out.println("---end:"+end);
				 */
				return "..." + builder.substring(start, end) + "...";

			} catch (StringIndexOutOfBoundsException exception) {
				exception.printStackTrace();
			}
		}
		return null;
	}

	public static void addToLog(String txt) {
		if (IndexControl.getLog().length() > 20000)
			IndexControl.getLog().delete(0, 10000);
		IndexControl.getLog().insert(0, System.lineSeparator());
		IndexControl.getLog().insert(0, txt);
	}
}
